package com.kkwrite.regimen.consumer.controller.income;

import com.kkwrite.regimen.common.constant.SortTypeEnum;
import com.kkwrite.regimen.common.entity.dto.OutDTO;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.kkwrite.regimen.common.constant.Constant.BOOLEAN_STRING_FALSE;
import static com.kkwrite.regimen.consumer.controller.constant.Constant.SERVICE_PREFIX;

/**
 * 收益模块接口
 *
 * @author jinying
 */
@Api(value = "收益模块")
@RestController
@RequestMapping("/income")
public class IncomeController {

    private static final Logger logger = LoggerFactory.getLogger(IncomeController.class);

    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @ApiOperation(value = "查询收益详情")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "page", value = "获取第page页数据", required = true, allowableValues = "[0, infinity]",
                            paramType = "query", dataType = "Long"),
                    @ApiImplicitParam(name = "size", value = "每页size条记录", required = true, allowableValues = "[1, infinity]",
                            paramType = "query", dataType = "int"),
                    @ApiImplicitParam(name = "sortType", value = "按时间排序的排序类型", defaultValue = "2",
                            allowableValues = "{1, 2}", paramType = "path", dataType = "int")
            })
    @GetMapping("/getIncome")
    public OutDTO getIncome(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
                            @PathVariable(required = false) Integer sortType, HttpServletRequest request) {
        String token = request.getHeader("token");
        Object userIdObj = redisTemplate.opsForHash().get(token, "userId");
        if (userIdObj == null) {
            return new OutDTO<>("false", "002", "token invalid");
        }
        if (page == null || page < 0 || size == null || size < 1) {
            return new OutDTO<>("false", "入参不合法");
        }
        if (!SortTypeEnum.isSortType(sortType)) {
            sortType = 2;
        }
        return restTemplate.getForObject(SERVICE_PREFIX + "/income/getIncome?page="
                + page + "&size=" + size + "&userId=" + userIdObj + "&sortType=" + sortType, OutDTO.class);
    }

    @GetMapping(value = "/count")
    @HystrixCommand(fallbackMethod = "countIncomeError")
    @ApiOperation(value = "统计用户收益接口", notes = "该接口不需要入参，后台根据token获取用户ID")
    public OutDTO countIncome(HttpServletRequest request) {
        String userId = (String) redisTemplate.opsForHash().get(request.getHeader("token"), "userId");
        if (userId == null) {
            return OutDTO.of(BOOLEAN_STRING_FALSE, "002", "token invalid", null);
        }
        return restTemplate.getForObject(SERVICE_PREFIX + "/income/count/" + userId, OutDTO.class);
    }

    public OutDTO countIncomeError(HttpServletRequest request, Throwable t) {
        logger.error("统计用户收益异常！异常信息：" + t.getMessage(), t);
        return OutDTO.of(BOOLEAN_STRING_FALSE, "服务异常！");
    }

    @GetMapping(value = "/extract")
    @HystrixCommand(fallbackMethod = "extractCashError")
    @ApiOperation(value = "用户提现接口")
    @ApiImplicitParam(name = "amount", value = "提现金额", required = true,
            paramType = "query", dataType = "double", allowableValues = "(0, infinity)")
    public OutDTO extractCash(@RequestParam Double amount, HttpServletRequest request) {
        String userId = (String) redisTemplate.opsForHash().get(request.getHeader("token"), "userId");
        if (userId == null) {
            return OutDTO.of(BOOLEAN_STRING_FALSE, "002", "token invalid", null);
        }
        if (amount <= 0) {
            return OutDTO.of(BOOLEAN_STRING_FALSE, "入参不合法！提现金额需大于0");
        }
        return restTemplate.getForObject(SERVICE_PREFIX + "/income/extract/" + userId + "?amount=" + amount, OutDTO.class);
    }

    public OutDTO extractCashError(Double amount, HttpServletRequest request, Throwable t) {
        logger.error("用户提现接口异常！异常信息：" + t.getMessage(), t);
        return OutDTO.of(BOOLEAN_STRING_FALSE, "用户提现接口异常！");
    }

}
